import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import { useDispatch } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
import { login } from '@/store/actions'; // 登录action

import logo from '@/assets/logo.png';
import styles from './index.module.scss';

const Login = (props) => {
  // console.log('login props', props);
  // 将dispatch注入到当前组件
  const dispatch = useDispatch();
  // 将history注入到当前组件
  const history = useHistory();
  // 获取 location
  const location = useLocation();
  // console.log('login的location', location);

  const onFinish = async (values) => {
    try {
      // 发起登录请求action
      await dispatch(login(values.mobile, values.code));
      // console.log('after dispatch');
      // 1. 登录成功跳转到首页 => 2.登录成功跳转到之前的页面
      history.replace(location.state ? location.state.from : '/home/index');
    } catch (error) {
      console.dir(error);
      if (error.response) {
        message.warn(error.response.data.message);
      } else {
        message.warn('网络错误');
      }
    }
  };

  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img src={logo} className="login-logo" />
        <Form
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            remember: true,
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不对' },
              { required: true, message: '请输入手机号' },
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              { len: 6, message: '验证码要6位' },
              { required: true, message: '请输入验证码' },
            ]}
          >
            <Input size="large" placeholder="请输入验证码" maxLength={6} />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked">
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              style={{
                width: '100%',
              }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
